package com.cat.binaryTree;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @author 曲大人的喵
 * @description https://leetcode.cn/problems/recover-binary-search-tree/
 * @create 2025/9/15 21:21
 * @since JDK17
 */

public class Solution50 {
    List<Integer> list = new ArrayList<>();
    int n = 0;
    void f(TreeNode root, boolean flag) {
        if (root == null) {
            return;
        }
        f(root.left, flag);
        if (!flag) {
            list.add(root.val);
        } else {
            root.val = list.get(n++);
        }
        f(root.right, flag);
    }

    public void recoverTree(TreeNode root) {
        f(root, false);
        Collections.sort(list);
        f(root, true);
    }
}
